<?php

namespace app\job\queue;

use app\common\enum\AliJobTypeEnum;
use app\common\enum\fp\PostAuditEnum;
use app\common\model\AliJob;
use app\common\model\fp\PostAudit;
use app\logic\es\fp\EsPost;
use think\facade\Log;
use think\queue\Job;
use app\common\library\aliyuns\MtsClient;
use app\common\model\fp\PostMedia;
use think\Exception;

class MpsSnapshotNotifyJob
{
    public function fire(Job $job, $data)
    {
        if ($job->attempts() > 3) {
            //通过这个方法可以检查这个任务已经重试了几次了
            $job->failed($data);
            $job->delete();
            return;
        }
        try {
            if ($data['state'] === "Success") {
                $jobId = $data['jobId'];
                $jobData = AliJob::where('job_id', $jobId)->find();
                if (!$jobData) {
                    throw new Exception('任务记录不存在:' . $jobId);
                }

                $jobList = MtsClient::getInstance()->querySnapshotJob($jobId);
                $snapshotJob = $jobList['SnapshotJobList']['SnapshotJob'][0] ?? [];
                if (!$snapshotJob) {
                    throw new Exception('截图任务不存在:' . $jobId);
                }
                $cover = urldecode($snapshotJob['SnapshotConfig']['OutputFile']['Object']);
                $count = $snapshotJob['Count'];
                $coverArr = [];
                for ($i = 1; $i <= $count; $i++) {
                    $formattedNumber = str_pad($i, 5, "0", STR_PAD_LEFT);
                    $coverArr[] = str_replace('{Count}', $formattedNumber, $cover);
                }

                //更新任务状态
                AliJob::where('id', $jobData['id'])->update([
                    'status' => 1,
                    'notify_result' => json_encode($data),
                    'update_time' => time()
                ]);

                //修改审核记录的截图状态
                PostAudit::initModel()->where('id', $jobData['audit_id'])->update(['snapshot_status' => 1, 'video_cover_url_bak' => json_encode($coverArr)]);

                //删除rabbitmq队列
                $job->delete();
            }
        } catch (\Throwable $e) {
            Log::channel('job')->error($e->getMessage() . PHP_EOL . $e->getTraceAsString());
            throw $e;
        }
    }
}